from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
import json # 用于处理JSON

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=True) # 邮箱可选
    password_hash = db.Column(db.String(128), nullable=False)
    avatar_url = db.Column(db.String(255), nullable=True) # 头像URL
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    # 预留字段
    bio = db.Column(db.Text, nullable=True)
    profile_info = db.Column(db.JSON, nullable=True) # 存储其他JSON格式信息

    conversations = db.relationship('Conversation', backref='user', lazy=True, cascade="all, delete-orphan")

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def to_dict(self, include_email=False):
        try:
            data = {
                'id': self.id,  # 现在直接使用 id
                'username': self.username,
                'avatar_url': self.avatar_url,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'bio': self.bio
            }
            if include_email:
                data['email'] = self.email
                
            # 如果 profile_info 可能是 None，需要处理
            if hasattr(self, 'profile_info') and self.profile_info is not None:
                data['profile_info'] = self.profile_info
                
            return data
        except Exception as e:
            print(f"Error in to_dict: {str(e)}")
            import traceback
            print(traceback.format_exc())
            return {'error': 'Error serializing user data'}

    def __repr__(self):
        return f'<User {self.username}>'

class Conversation(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) # 外键关联User表
    title = db.Column(db.String(255), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    messages_json = db.Column(db.Text, nullable=False) # 消息存储为JSON字符串

    @property
    def messages(self):
        try:
            return json.loads(self.messages_json)
        except json.JSONDecodeError:
            return [] # 如果解析失败返回空列表

    @messages.setter
    def messages(self, messages_list):
        self.messages_json = json.dumps(messages_list)

    @staticmethod
    def create_conversation(user_id, messages, title=None):
        if not title and messages:
            user_message = next((msg['content'][:30] for msg in messages if msg['role'] == 'user'), None)
            title = f"{user_message}..." if user_message else "新对话"
        
        conv = Conversation(
            user_id=user_id, # 关联用户ID
            title=title or "新对话",
            messages=messages
        )
        return conv

    def to_dict(self, include_messages=True):
        data = {
            'id': self.id,  # 直接使用数据库 ID
            'title': self.title,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat(),
            'user_id': self.user_id  # 直接使用用户 ID
        }
        if include_messages:
            data['messages'] = self.messages
        return data

    def __repr__(self):
        return f'<Conversation {self.id}>'